package com.example.caimogu.businessapp;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.android.gms.cast.MediaStatus;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

public class AddNewGoodsActivity extends AppCompatActivity {

    private EditText et_goodsName;
    private EditText et_goodsprice;
    private EditText et_goodsSelltime;
    private EditText et_goodsInfo;
    private static final int TAKE_PHOTO = 1;
    private static final int CROP_PHOTO = 2;
    private static final int CHOOSE_PHOTO = 3;

    private Uri imageUri;
    private ImageView picture;
    private String fileName;
    private ArrayList<String> photoList;//保存每次拍照的路径




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_new_goods);
        init_View();
    }

    private void init_View() {
        et_goodsName = (EditText)findViewById(R.id.et_ms_addnewgoods_name);
        et_goodsprice = (EditText)findViewById(R.id.et_ms_addnewgoods_price);
        et_goodsSelltime = (EditText)findViewById(R.id.et_ms_addnewgoods_selltime);
        et_goodsInfo = (EditText)findViewById(R.id.et_ms_addnewgoods_info);

        picture = (ImageView) findViewById(R.id.iv_ms_addnewgoods_pic);
        photoList = new ArrayList<>();

    }
    //添加图片--拍照
    public void addnewgoods_pic(View view){
        //Toast.makeText(AddNewGoodsActivity.this,"change pic",Toast.LENGTH_SHORT).show();
        File outputImage = new File(Environment.getExternalStorageDirectory(),"output_image.png");
        try{
            if(outputImage.exists()){
                outputImage.delete();
            }
            outputImage.createNewFile();

        }catch (Exception e){
            e.printStackTrace();
        }
        imageUri = Uri.fromFile(outputImage);
        Log.i("caimogu", "拍照存储位置：" + imageUri.toString());
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, TAKE_PHOTO);


    }
    //添加图片--从文件选取
    public void addnewgoods_localpic(View view){
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_PHOTO);
    }

    //提交填写好的一个商品
    public void commitNewGoods(View view){
        Bundle bundle = new Bundle();

        if(et_goodsName.getText().toString().length()==0 ||
                et_goodsprice.getText().toString().length()==0 ||
                et_goodsSelltime.getText().toString().length()==0 ||
                et_goodsInfo.getText().toString().length()==0){
            Toast.makeText(this,"信息没写全！",Toast.LENGTH_SHORT).show();

            return;
        }


        bundle.putStringArrayList("photoList",photoList);
        bundle.putString("goodsName", et_goodsName.getText().toString());
        bundle.putString("goodsprice", et_goodsprice.getText().toString());
        bundle.putString("goodsSelltime", et_goodsSelltime.getText().toString());
        bundle.putString("goodsInfo", et_goodsInfo.getText().toString());
        Intent intent = new Intent();
        intent.putExtras(bundle);
        setResult(Activity.RESULT_OK, intent);
        Log.i("caimogu", "onActivityResult");
        this.finish();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode){
            case TAKE_PHOTO:
                if(resultCode == RESULT_OK){
                    Intent intent = new Intent("com.android.camera.action.CROP");
                    intent.setDataAndType(imageUri, "image/*");
                    intent.putExtra("scale", true);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    startActivityForResult(intent,CROP_PHOTO);
                }
                break;
            case CROP_PHOTO:
                if(resultCode == RESULT_OK){
                    try{
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        //Bitmap bitmap = BitmapFactory.decodeFile(imageUri.toString());
                        picture.setImageBitmap(bitmap);
                        savePicInLocal(bitmap);

                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                break;
            case CHOOSE_PHOTO:
                if(resultCode == RESULT_OK){
                   // handleImageBeforeKitkat(data);
                    if(Build.VERSION.SDK_INT >=19){
                        handleImageOnKitkat(data);
                    }else{
                        break;
                    }
                }
                break;
            default:
                break;
        }
    }

    //4.4以上版本
    //通过uri-------------获取----------绝对路径------
    @TargetApi(19)
    private void handleImageOnKitkat(Intent data) {
        Log.i("caimogu","我是4.4以上版本");
        String imagePath = null;
        Uri uri = data.getData();

        imagePath = getRealFilePath(uri);
        photoList.add(imagePath);
        displayImage(imagePath);
    }

    public  String getRealFilePath(   Uri uri ) {
        if ( null == uri ) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if ( scheme == null )
            data = uri.getPath();
        else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
            data = uri.getPath();
        } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
            Cursor cursor = getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null );
            if ( null != cursor ) {
                if ( cursor.moveToFirst() ) {
                    int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA );
                    if ( index > -1 ) {
                        data = cursor.getString( index );
                    }
                }
                cursor.close();
            }
        }
        return data;
    }


    //显示图片
    private void displayImage(String imagePath) {
        if(imagePath != null){
            Bitmap bitMap = BitmapFactory.decodeFile(imagePath);
            picture.setImageBitmap(bitMap);
        }else{
            Toast.makeText(this,"failed to get image",Toast.LENGTH_SHORT).show();
        }

    }


    private void savePicInLocal(Bitmap bitmap) {
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        ByteArrayOutputStream baos = null; // 字节数组输出流
        try {
            baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
            byte[] byteArray = baos.toByteArray();// 字节数组输出流转换成字节数组
            String saveDir = Environment.getExternalStorageDirectory()
                    + "/GoodsPic";
            File dir = new File(saveDir);
            if (!dir.exists()) {
                dir.mkdir(); //创建文件夹
            }
             fileName = saveDir + "/" + System.currentTimeMillis() + ".png";
            Log.i("caimogu",fileName);
            File file = new File(fileName);
            file.delete();
            if (!file.exists()) {
                file.createNewFile();// 创建文件
                Log.e("PicDir", file.getPath());
                //Toast.makeText(TackPhoto.this, fileName, Toast.LENGTH_LONG).show();
            }
            // 将字节数组写入到刚创建的图片文件中
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(byteArray);
            photoList.add(fileName);
            Log.i("caimogu", fileName);

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (baos != null) {
                try {
                    baos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

    }
}
